<?php
class CategoryModel extends Model{
	
	private $table;
	
	public function __construct(){
		parent::__construct();
		
		$this->table = C('db_table_prefix').'categories';
	}
	
	/**
	 * 获取分类信息
	 */
	public function getCategories($id=null){
		$categories = array();
		$sql = "SELECT `id`,`name`,`description`,`order` FROM `{$this->table}` WHERE `status`=1";
		if($id){
			$sql .= " AND `id`='{$id}'";
		}
		$sql .= " ORDER BY `order` ASC,`id` ASC";
		$categories = $this->query($sql);
		
		return $categories;
	}
	
	/**
	 * 获取单条分类信息
	 */
	public function getCategoryById($id){
		if(empty($id)){
			return false;
		}
		$category = $this->getCategories($id);
		
		return $category[0];
	}
		
	/**
	 * 添加分类
	 */
	public function addCategory($data){
		$time = time();
		$sql = "INSERT INTO `{$this->table}`
			(`name`,`description`,`order`,`ctime`,`utime`)
			VALUES ('{$data['name']}','{$data['description']}','{$data['order']}','{$time}','{$time}')";
		$result = $this->execute($sql);
		
		return $result;
	}
	
	/**
	 * 编辑分类
	 * @param array $data array('id'=>'','name'=>'','desc'=>'')
	 * @return boolean true or false
	 */
	public function editCategory($data){
		if(empty($data['id'])){
			return false;
		}
		$utime = time();
		$sql = "UPDATE `{$this->table}` SET `name`='{$data['name']}',`description`='{$data['description']}',`utime`='{$utime}' WHERE `id`='{$data['id']}' LIMIT 1";
		$result = $this->execute($sql);

		return $result;
	}
	
	/**
	 * 删除分类
	 * @param int $id
	 * @return boolean true or false
	 */
	public function delCategory($id){
		if(empty($id)){
			return false;
		}
		$sql = "UPDATE `{$this->table}` SET `status`='0' WHERE `id`='{$id}' LIMIT 1";
		$result = $this->execute($sql);
		
		return $result;
	}
	
}